﻿using Zhp.Common.Appsetting;

namespace Zhp.Api.Extensions
{
    public static class CorsSetup
    {
        public static void AddCorsSetup(this IServiceCollection services)
        {
            var options = services.GetOptions<CorsOptions>();
            services.AddCors(c =>
            {
                if (options.EnableAll)
                {
                    //允许任意跨域请求
                    c.AddPolicy(options.Name, policy =>
                    {
                        policy.SetIsOriginAllowed(_ => true).AllowAnyMethod().AllowAnyHeader().AllowCredentials().WithExposedHeaders("Content-Disposition");
                    });
                }
                else
                {
                    c.AddPolicy(options.Name, policy =>
                    {
                        policy.WithOrigins(options.Policy.Select(x => x.Domain).ToArray()).AllowAnyHeader().AllowAnyMethod().AllowCredentials().WithExposedHeaders("Content-Disposition");
                    });
                }
            });
        }

        public static void UseCorsMiddleware(this IApplicationBuilder app)
        {
            var options = AppSettingHelper.GetOptions<CorsOptions>();
            app.UseCors(options.Name);
        }
    }

}
